package se.sll.itintegration.catalogue.gui.service.view.capacity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import se.sll.itintegration.catalogue.gui.service.view.capacity.CapacityViewProduct.Availability;
import se.sll.service.catalogue.common.Translator;
import se.sll.service.catalogue.common.rest.request.CapacityCreateRequest;

public class CapacityCreateRequestListProductTranslator implements Translator<CapacityViewProduct, List<CapacityCreateRequest>> {
    private final String hsaID;

    public CapacityCreateRequestListProductTranslator(String hsaID) {
        this.hsaID = hsaID;
    }

    @Override
    public List<CapacityCreateRequest> translate(CapacityViewProduct from) {
        return translateTo(from, new ArrayList<CapacityCreateRequest>());
    }

    @Override
    public List<CapacityCreateRequest> translateTo(CapacityViewProduct from, List<CapacityCreateRequest> to) {
        String productId = from.getId();
        Date validTo = from.getValidTo();

        addCreateRequest(to, productId, validTo, CapacityConstants.CODESYSTEM_CAPACITY,
                CapacityConstants.CODE_AVAILABLE_CAPACITY, translate(from.getAvailableCrossRegionCapacity()));
        addCreateRequest(to, productId, validTo, CapacityConstants.CODESYSTEM_CAPACITY,
                CapacityConstants.CODE_REFERRAL_INFORMATION, from.getReferralInfo());

        CapacityCreateRequestListCapacityTranslator translator = new CapacityCreateRequestListCapacityTranslator(hsaID, productId, validTo);
        List<CapacityViewCapacity> capacities = from.getCapacities();
        for (CapacityViewCapacity capacity : capacities) {
            translator.translateTo(capacity, to);
        }
        return to;
    }

    private String translate(Availability availability) {
        String value;
        if (availability == Availability.YES) {
            value = "true";
        } else if (availability == Availability.NO) {
            value = "false";
        } else {
            value = null;
        }
        return value;
    }

    private void addCreateRequest(List<CapacityCreateRequest> dst, String productId, Date validTo, String codeSystem, String code, String value) {
        if (value != null) {
            CapacityCreateRequest request = new CapacityCreateRequest();
            request.setHsaID(hsaID);
            request.setProduct(productId);
            request.setValidTo(validTo);
            request.setCodeSystem(codeSystem);
            request.setCode(code);
            request.setValue(value);
            dst.add(request);
        }
    }
}
